package vip.george.security.advice;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import vip.george.security.constant.InterfaceSecurityConstant;
import vip.george.security.utils.AesUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestControllerAdvice
public class EncryptResponseBodyAdvice implements ResponseBodyAdvice<Object> {



    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 可以通过注解或其他条件判断哪些接口需要加密
        return true; // 这里对所有接口返回都加密
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
                                  ServerHttpResponse response) {
        // 调用你的加密方法
        Object aesKey = ((ServletServerHttpRequest) request).getServletRequest().getAttribute(InterfaceSecurityConstant.AES_KEY_REQUEST_ATTRIBUTE).toString();
        if (Objects.isNull(aesKey)) {
            return body;
        }
        String encryptResponseStr = AesUtil.encrypt(JSON.toJSONString(body, JSONWriter.Feature.WriteMapNullValue), aesKey.toString());
        Map<String, Object> map = new HashMap<>();
        map.put("res", encryptResponseStr);
        return map;
    }
}
